package com.ytzl.itrip.controller;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.ytzl.itrip.common.DtoUtil;
import com.ytzl.itrip.common.EmptyUtils;
import com.ytzl.itrip.common.ErrorCode;
import com.ytzl.itrip.common.FtpUtil;
import com.ytzl.itrip.dto.Dto;
import com.ytzl.itrip.pojo.ItripComment;
import com.ytzl.itrip.pojo.ItripHotel;
import com.ytzl.itrip.pojo.ItripImage;
import com.ytzl.itrip.pojo.ItripUser;
import com.ytzl.itrip.vo.ItripLabelDicVO;
import com.ytzl.itrip.vo.comment.ItripAddCommentVO;
import com.ytzl.itrip.vo.order.ItripHotelDescVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.plugin.extension.ExtensionUtils;
import ytx.org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 评论相关接口
 * Created by sam on 2018/2/10.
 */
@Controller
@Api(tags = "评论相关模块业务")
@RequestMapping("/api/comment")
public class SystemCommentController extends BaseController {

    @ApiOperation(value = "根据酒店Id获取相关信息（酒店名称，星级）", httpMethod = "GET", produces = "application/json", response = Dto.class, notes = "查询酒店信息根据酒店Id")
    @RequestMapping(value = "/gethoteldesc/{hotelId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto gethoteldesc(@PathVariable @ApiParam(required = true, value = "hotelId", name = "酒店Id") String hotelId) {
        try {
            if (EmptyUtils.isNotEmpty(hotelId)) {
                ItripHotel itripHotel = itripHotelService.getItripHotelById(Long.valueOf(hotelId));
                ItripHotelDescVO itripHotelDescVO = new ItripHotelDescVO();
                itripHotelDescVO.setId(itripHotel.getId());
                itripHotelDescVO.setHotelName(itripHotel.getHotelName());
                itripHotelDescVO.setHotelLevel(itripHotel.getHotelLevel());
                return DtoUtil.returnDataSuccess(itripHotelDescVO);
            } else {
                return DtoUtil.returnFail("请传递参数", ErrorCode.AUTH_UNKNOWN);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("", ErrorCode.BIZ_QUERY_GET_HOTEL_DESC_FAILED);
        }
    }

    @ApiOperation(value = "查询字典表找到酒店类型的子级", httpMethod = "GET", response = Dto.class, produces = "application/json", notes = "查询出游类型的子级元素")
    @RequestMapping(value = "gettraveltype", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto getTravelType() {
        Long parentId = 107L;
        //查询根据父级Id
        try {
            List<ItripLabelDicVO> itripLabelDicVOS = itripLabelDicService.getItripLabelDicByParentId(parentId);
            return DtoUtil.returnDataSuccess(itripLabelDicVOS);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.BIZ_ITRIP_TYPE_LIST_FAILED);
        }
    }

    @ApiOperation(value = "文件上传", httpMethod = "POST", produces = "multipart/form-data", response = Dto.class, notes = "上传评论图片，最多支持4张图片同时上传，格式为：jpg、jpeg、png，大小不超过5M" +
            "<p style=‘color:red’>注意：input file 中的name不可重复 e:g : file1 、 file2 、 fileN</p>" +
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>" +
            "<p>100006 : 文件上传失败 </p>" +
            "<p>100007 : 上传的文件数不正确，必须是大于1小于等于4 </p>" +
            "<p>100008 : 请求的内容不是上传文件的类型 </p>" +
            "<p>100009 : 文件大小超限 </p>")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Dto uploadPic(HttpServletRequest request) {
        //将http request 转换为multipart request
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        List<String> dataList = new ArrayList<>();
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multRequest = (MultipartHttpServletRequest) request;
            int fileCount = 0;
            try {
                fileCount = multRequest.getFileMap().size();
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("文件大小超限", ErrorCode.BIZ_UPLOAD_FILE_SIZE_INVALID);
            }
            if (fileCount > 0 && fileCount <= 4) {
                String token = request.getHeader("token");
                ItripUser currentUser = validationToken.getCurrentUser(token);
                if (null != currentUser) {
                    Iterator<String> fileNames = multRequest.getFileNames();
                    while (fileNames.hasNext()) {
                        //此时调用了getFile方法，文件才被解析
                        MultipartFile file = multRequest.getFile(fileNames.next());
                        if (file != null) {
                            //获取文件名
                            String myFileName = file.getOriginalFilename();
                            //获取文件后缀
                            String extName = FilenameUtils.getExtension(myFileName);
                            if (myFileName.trim() != "" && (extName.equalsIgnoreCase("jpg") || extName.equalsIgnoreCase("jpeg") || extName.equalsIgnoreCase("png"))) {
                                //生成新的文件名
                                //命名规则 用户Id+当前时间+随机数
                                String newFileName = currentUser.getId() + "-" + System.currentTimeMillis() + "-" + ((int) (Math.random() * 100000000)) + "." + extName;
                                //上传
                                boolean uploadFile = false;
                                try {
                                    uploadFile = FtpUtil.uploadFile(systemConfig.getFtpHost(), systemConfig.getFtpPort(), systemConfig.getFtpUserName(), systemConfig.getFtpPassword(), systemConfig.getFileUploadPath(), "/comment", newFileName, file.getInputStream());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                if (uploadFile) {
                                    //文件访问url
                                    String url = systemConfig.getVisitImgUrl() + newFileName;
                                    dataList.add(url);
                                }
                            }
                        }
                    }
                    return DtoUtil.returnDataSuccess(dataList);
                } else {
                    return DtoUtil.returnFail("文件上传失败", ErrorCode.BIZ_UPLOAD_FILE_FAILED);
                }
            } else {
                return DtoUtil.returnFail("上传的文件数不正确，必须是大于1小于等于4", ErrorCode.BIZ_UPLOAD_FILE_MUST_BE_0_TO_4);
            }
        } else {
            return DtoUtil.returnFail("请求的内容不是上传文件的内容", ErrorCode.BIZ_UPLOAD_FILE_NOT_MULTIPART);
        }
    }

    @ApiOperation(value = "删除图片根据图片名称", httpMethod = "POST", response = Dto.class, notes = "删除传递图片名称" +
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>" +
            "<p>100010 : 文件不存在，删除失败 </p>" +
            "<p>100000 : token失效，请重登录 </p>")
    @RequestMapping(value = "/delpic", method = RequestMethod.POST)
    @ResponseBody
    public Dto delPic(HttpServletRequest request, @RequestParam @ApiParam(value = "imgName", name = "图片名称") String imgName) {
        //验证token
        String token = request.getHeader("token");
        ItripUser currentUser = validationToken.getCurrentUser(token);
        if (null != currentUser) {
            String path = systemConfig.getFileUploadPath() + "/comment/" + imgName;
            boolean uploadFile = FtpUtil.deleteFile(systemConfig.getFtpHost(), systemConfig.getFtpPort(), systemConfig.getFtpUserName(), systemConfig.getFtpPassword(), path);
            if (uploadFile) {
                return DtoUtil.returnSuccess("文件删除成功");
            } else
                return DtoUtil.returnFail("文件不存在，删除失败", ErrorCode.BIZ_DELETE_UPLOAD_FILE_FAILED);
        } else {
            return DtoUtil.returnFail("Token已失效", ErrorCode.BIZ_TOKEN_INVALID);
        }
    }

    @ApiOperation(value = "新增评论接口", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "新增评论信息" +
            "<p style=‘color:red’>注意：若有评论图片，需要传图片路径</p>" +
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>" +
            "<p>100003 : 新增评论失败 </p>" +
            "<p>100004 : 不能提交空，请填写评论信息</p>" +
            "<p>100005 : 新增评论，订单ID不能为空</p>" +
            "<p>100000 : token失效，请重登录 </p>")
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto addComment(@RequestBody ItripAddCommentVO itripAddCommentVO, HttpServletRequest request) {
        if (EmptyUtils.isEmpty(itripAddCommentVO))
            return DtoUtil.returnFail("不能提交空，请填写评论信息", ErrorCode.BIZ_ADD_COMMENT_IS_NOT_NULL);
        if (EmptyUtils.isEmpty(itripAddCommentVO.getOrderId()))
            return DtoUtil.returnFail("订单Id不能为空", ErrorCode.BIZ_ADD_COMMENT_IS_NOT_ORDERID);
        String token = request.getHeader("token");
        ItripUser currentUser = validationToken.getCurrentUser(token);
        if (EmptyUtils.isNotEmpty(currentUser)) {
            //VO类转换为数据库对应的实体类
            ItripComment itripComment = new ItripComment();
            BeanUtils.copyProperties(itripAddCommentVO, itripComment);
            itripComment.setCreatedBy(currentUser.getId());
            itripComment.setUserId(currentUser.getId());
            itripComment.setCreationDate(new Date());
            //创建图片实体
            List<ItripImage> itripImages = new ArrayList<>();
            for (int i = 0; i < itripAddCommentVO.getItripImages().length; i++) {
                ItripImage itripImage = itripAddCommentVO.getItripImages()[i];
                itripImage.setCreatedBy(currentUser.getId());
                itripImage.setCreationDate(new Date());
                itripImage.setPosition(i);
                itripImage.setType("2");
                itripImages.add(itripImage);
            }
            //数据入库
            try {
                itripCommentService.saveItripCommentAndItripImage(itripComment, itripImages);
                return DtoUtil.returnSuccess("添加评论成功");
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("添加评论失败", ErrorCode.BIZ_ADD_COMMENT_FAILED);
            }
        } else
            return DtoUtil.returnFail("Token已失效", ErrorCode.BIZ_TOKEN_INVALID);
    }

}
